//
//  NSString+Extension.m
//  KYViedoApp
//
//  Created by 张浩 on 16/5/17.
//  Copyright © 2016年 KingNet. All rights reserved.
//

NSString *settingRoute(NSString *startPoint, NSString *endPoint) {
    return [NSString stringWithFormat:@"%@_%@", startPoint, endPoint];
}

NSString *mutablePage(NSString *page ,long tvid) {
    return [NSString stringWithFormat:@"%@#%ld", page, tvid];
}



NSString *mutablePosition(long position,long index) {
    return [NSString stringWithFormat:@"%ld", position+index];
}
NSString *mutablePositionWithCategoryId(long position,long index, long categoryId) {
    return [NSString stringWithFormat:@"%ld#%ld",position+index, categoryId];
}

#import "NSString+Extension.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Extension)

+ (NSString *)appVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
    
- (NSString *)md5 {
    const char *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

+ (NSString *)stringByInt:(long)num {
    return [NSString stringWithFormat:@"%ld",num];
}

+ (NSString *)stringByUnsignedInt:(long)num {
    return [NSString stringWithFormat:@"%lu", num];
}

+ (NSString *)stirngByFloat:(float)num {
    return [NSString stringWithFormat:@"%f",num];
}
+ (NSString *)stirngByDouble:(double)num {
    return [NSString stringWithFormat:@"%lf",num];
}

+ (NSString *)stringForCount_W:(long long)count {
    if (count > 10000) {
        return [NSString stringWithFormat:@"%.2f万",count * 0.0001];
    }
    return [NSString stringWithFormat:@"%lld",count];
}

+ (NSString *)stringForCount_Individual:(long long)count {
    if (count > 10000) {
        return [NSString stringWithFormat:@"%.2f万",count * 0.0001];
    }
    return [NSString stringWithFormat:@"%lld",count];
}

#pragma mark -判断空串
+ (BOOL)isEmptyString:(NSString *)str {
    if (!str) {
        return YES;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *string = [str stringByTrimmingCharactersInSet:set];
        if (string.length == 0) {
            return YES;
        } else {
            return NO;
        }
    }
}

#pragma mark - 表情类

- (BOOL)isContainEmojiUnicode {
    BOOL returnValue = NO;
    const unichar hs = [self characterAtIndex:0];
    // surrogate pair
    if (0xd800 <= hs && hs <= 0xdbff) {
        if (self.length > 1) {
            const unichar ls = [self characterAtIndex:1];
            const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
            if (0x1d000 <= uc && uc <= 0x1f918) {
                returnValue = YES;
            }
        }
    } else if (self.length > 1) {
        const unichar ls = [self characterAtIndex:1];
        if (ls == 0x20e3 || ls == 0xFE0F || ls == 0xd83c) {
            returnValue = YES;
        }
    } else {
        // non surrogate
        if (0x2100 <= hs && hs <= 0x27ff) {
            returnValue = YES;
        } else if (0x2B05 <= hs && hs <= 0x2b07) {
            returnValue = YES;
        } else if (0x2934 <= hs && hs <= 0x2935) {
            returnValue = YES;
        } else if (0x3297 <= hs && hs <= 0x3299) {
            returnValue = YES;
        } else if (hs == 0xa9 || hs == 0xae ||
                   hs == 0x303d || hs == 0x3030 ||
                   hs == 0x2b55 || hs == 0x2b1c ||
                   hs == 0x2b1b || hs == 0x2b50) {
            returnValue = YES;
        }
    }
    return returnValue;
}

/**
 编码
     单个表情utf16编码后的格式
     如果为双字节  如\ue64a\ue31a 将\u去掉前后端加上边界区分，如[/e64ae31a/]
     如果为单字节  如\ue31a 将\u去掉前后端加上边界区分，如[/e31a/]
 解码
     先把边界[/  /]区分出来，将边界内的字符串转换为UTF16编码后的格式 如\ue64a\ue31a
 示例
    “表情评论测试\ue64a\ue31a评论结束” 编码后的应该为 “表情评论测试[/e64ae31a/]评论结束”，中文不能被编码，要用明文传输
 */
- (NSString*) encoderEmoji {
    NSMutableString *result = [[NSMutableString alloc] init];
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length)
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                              //emoji length is 2  replace emoji with emptyString
                              //bug  第三方输入法的表情可能 存在长度为4等的表情
                              if (substring.length >= 2) {
                                  const char * strData = [substring cStringUsingEncoding:NSNonLossyASCIIStringEncoding];
                                  NSData *data = [[NSData alloc] initWithBytes:strData length:strlen(strData)];
                                  NSString *temp = [[NSString alloc] initWithCString:data.bytes
                                                                            encoding:NSUTF8StringEncoding];
                                  if (temp.length > 0) {
                                      [result appendString:@"[/"];
                                      [result appendString:[temp stringByReplacingOccurrencesOfString:@"\\u" withString:@""]];
                                      [result appendString:@"/]"];
                                  }
                              } else if (substring.length > 0) {
                                  if (substring.length == 1 && [substring isContainEmojiUnicode]) {
                                      const char * strData = [substring cStringUsingEncoding:NSNonLossyASCIIStringEncoding];
                                      NSData *data = [[NSData alloc] initWithBytes:strData length:strlen(strData)];
                                      NSString *temp = [[NSString alloc] initWithCString:data.bytes
                                                                                encoding:NSUTF8StringEncoding];
                                      if (temp.length > 0) {
                                          [result appendString:@"[/"];
                                          [result appendString:[temp stringByReplacingOccurrencesOfString:@"\\u" withString:@""]];
                                          [result appendString:@"/]"];
                                      }
                                  }else
                                      [result appendString:substring];
                              }
                          }];
    return result;
    
//    NSData *data = [self dataUsingEncoding:NSNonLossyASCIIStringEncoding];
//    NSString *valueUnicode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    return valueUnicode;
}

- (NSString*) decoderEmoji {
    if (self.length <= 0) {
        return self;
    }
    NSMutableString *result = [[NSMutableString alloc] init];
    NSString *qrcodeStr = @"\\[/([a-zA-Z0-9]{4}){1,}/\\]";
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:qrcodeStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray <NSTextCheckingResult *>*matches = [regex matchesInString:self
                                                              options:0
                                                                range:NSMakeRange(0, [self length])];
    if (matches.count == 0) {
        return self;
    }
    matches = [matches sortedArrayUsingComparator:^NSComparisonResult(NSTextCheckingResult * _Nonnull obj1, NSTextCheckingResult *  _Nonnull obj2) {
        NSRange range1 = obj1.range;
        NSRange range2 = obj2.range;
        return range1.location >= range2.location;
    }];
    [matches enumerateObjectsUsingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSRange range = obj.range;
        if (idx == 0) {
            if (range.location > 0) {
                NSString *stringPre = [self substringToIndex:range.location];
                if (stringPre) {
                    [result appendString:stringPre];
                }
            }
        }else if (idx >= 1) {//  [/[/d83dde02]]
            NSRange rangePre = matches[idx-1].range;
            if (range.location > rangePre.location+rangePre.length) {
                NSInteger start = rangePre.location+rangePre.length;
                NSString *stringPre = [self substringWithRange:NSMakeRange(start, range.location - start)];
                if (stringPre.length > 0) {
                    [result appendString:stringPre];
                }
            }
        }
        NSString *stringRange = [self substringWithRange:range];
        if (stringRange.length > 4 &&
            [stringRange hasPrefix:@"[/"] &&
            [stringRange hasSuffix:@"/]"]) {
            NSString *temp = [stringRange substringWithRange:NSMakeRange(2, stringRange.length-4)];
            NSMutableString *tempEnd = [NSMutableString string];
            while (temp.length >= 4) {
                [tempEnd appendFormat:@"\\u%@",[temp substringToIndex:4]];
                temp = [temp substringFromIndex:4];
            }
            NSData *newdata=[tempEnd dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSString *rk =[[NSString alloc] initWithData:newdata encoding:NSNonLossyASCIIStringEncoding];
            if (rk) {
                [result appendString:rk];
            }else {
                [result appendString:stringRange];
            }
        }else
            [result appendString:stringRange];
        //  [/[/d83dde02]]
        if (idx == matches.count-1) {
            if (range.location+range.length < self.length) {
                NSInteger start = range.location+range.length;
                NSString *stringPre = [self substringWithRange:NSMakeRange(start, self.length - start)];
                if (stringPre.length > 0) {
                    [result appendString:stringPre];
                }
            }
        }
    }];
    return result;
    
//    NSData *dataa = [self dataUsingEncoding:NSUTF8StringEncoding];
//    NSString *valueEmoj = [[NSString alloc] initWithData:dataa encoding:NSNonLossyASCIIStringEncoding];
//    return valueEmoj;
}

- (CGSize)sizeWithFont:(UIFont *)font maxWidth:(CGFloat)maxWidth;
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxWidth, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font
{
    return [self sizeWithFont:font maxWidth:MAXFLOAT];
}


@end

